package com.qiyu.security.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public abstract class JwtUtil {
    
    /**
     * 过期时间
     */
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;
    
    private static final String SECRET = "DX_ACTIVITY";
    
    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static void verify(String token, String scene) {
        //根据密码生成JWT效验器
        Algorithm algorithm = Algorithm.HMAC256(SECRET + scene);
        JWTVerifier verifier = JWT.require(algorithm).build();
        //效验TOKEN
        verifier.verify(token);
    }
    
    /**
     * 获取用户ID
     *
     * @param token 密钥
     * @return
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    
    /**
     * 生成签名,7天后过期
     *
     * @param id 用户id
     * @return 加密的token
     */
    public static String sign(String id, String scene) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET + scene);
        return JWT.create()
                .withSubject(id)
                .withIssuedAt(nowDate)
                .withExpiresAt(expireDate)
                .sign(algorithm);
    }
}
